<template>
    <div class="nav-bar">
        <div class="nav-menu">
            <div class="nav-menu-item-title">
                <div style="margin-right: 10px;"><el-image :src="require('@/assets/logo.svg')"
                        style="width: 40px;height: 40px;" class="logo"></el-image></div>
                <div style="font-size: 20px;font-weight: 600;">论坛管理系统</div>
            </div>
            <div class="nav-menu-item" @click="$router.push('/home')">
                首页
            </div>
            <div class="nav-menu-item">
                <div class="menu-item">
                    <el-dropdown placement="bottom" @command="handleCommand" trigger="hover">
                        <span style="font-size: 16px;color: #303133;">分类</span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="item, index in articleCategoryList" :index="index"
                                :command="item.id">
                                {{ item.name }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>
            <div class="nav-menu-item" @click="$router.push('/resources')">
                资源中心
            </div>
        </div>
        <div class="user-section">
            <template v-if="!isLoggedIn">
                <el-button size="medium" type="text" round @click="showLoginDialog">登录</el-button>
                <el-button size="medium" type="text" round @click="showRegisterDialog">注册</el-button>
            </template>
            <template v-else>
                <div class="el-dropdown-link">
                    <el-avatar :size="40" :src="userInfo?.avatar"></el-avatar>
                    <span @click="$router.push('/user/space')" style="margin-right: 20px;">{{ userInfo.nickName
                        }}</span>
                    <el-button type="danger" size="mini" round @click="logout">退出登录</el-button>
                </div>
            </template>
        </div>

        <!-- 登录弹窗 -->
        <el-dialog title="用户登录" :visible.sync="loginDialogVisible" width="400px" center>
            <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <div>
                        <el-input v-model="loginForm.code" auto-complete="off" style="width: 63%"
                            @keyup.enter.native="handleLogin">
                        </el-input>
                        <div class="login-code">
                            <img :src="codeImgUrl" @click="getCode" class="login-code-img" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleLogin" style="width: 100%" :loading="loading">登录</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 注册弹窗 -->
        <el-dialog title="用户注册" :visible.sync="registerDialogVisible" width="400px" center>
            <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="password2">
                    <el-input v-model="registerForm.password2" type="password" placeholder="请再次输入密码"></el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <div>
                        <el-input v-model="registerForm.code" auto-complete="off" style="width: 63%"
                            @keyup.enter.native="handleRegister">
                        </el-input>
                        <div class="login-code">
                            <img :src="codeImgUrl" @click="getCode" class="login-code-img" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleRegister" style="width: 100%"
                        :loading="loading">注册</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { getLogin, getRegister, getEmailSend, getImgCode, getUserInfo, getLogout, reqArticleCategoryList } from '@/api';

export default {
    name: 'NavBar',
    data() {
        // 密码确认验证
        const validateConfirmPassword = (rule, value, callback) => {
            if (value !== this.registerForm.password) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };

        return {
            activeIndex: '/',
            loading: false,
            loginDialogVisible: false,
            registerDialogVisible: false,
            codeImgUrl: "",
            loginForm: {
                username: '',
                password: '',
                code: null,
                uuid: null
            },
            registerForm: {
                username: '',
                password: '',
                password2: '',
                code: '',
                uuid: null,
            },
            emailCodeDisabled: false,
            emailCodeText: '发送验证码',
            countdown: 60,
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' }
                ]
            },
            registerRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                password2: [
                    { required: true, message: '请确认密码', trigger: 'blur' },
                    { validator: validateConfirmPassword, trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' }
                ]
            },
            deliveryRecords: [], // 投递记录数据
            isLoggedIn: false, // 是否已登录
            userInfo: {},
            articleCategoryList: []
        }
    },
    mounted() {
        this.getArticleCategoryList();
        this.getCode();
        this.judgeIsLogin();
    },
    watch: {
        '$route'(to) {
            this.activeIndex = to.path
        }
    },
    methods: {
        getArticleCategoryList() {
            reqArticleCategoryList({
                pageNum: 1,
                pageSize: 1000
            }).then(res => {
                this.articleCategoryList = res.rows;
            })
        },
        handleCommand(command) {
            this.$router.push(`/category?categoryId=${command}`);
        },
        getCode() {
            getImgCode().then(res => {
                this.codeImgUrl = "data:image/gif;base64," + res.img
                if (this.registerDialogVisible) {
                    this.registerForm.uuid = res.uuid
                } else {
                    this.loginForm.uuid = res.uuid
                }
            })
        },
        async sendEmailCode() {
            if (!this.registerForm.email) {
                this.$message.warning('请输入邮箱地址');
                return;
            }

            try {
                await getEmailSend(this.registerForm.email);
                this.$message.success('验证码已发送');
                this.emailCodeDisabled = true;
                this.startCountdown();
            } catch (error) {
            }
        },
        startCountdown() {
            this.countdown = 60;
            const timer = setInterval(() => {
                this.countdown--;
                this.emailCodeText = `${this.countdown}秒后重试`;
                if (this.countdown <= 0) {
                    clearInterval(timer);
                    this.emailCodeDisabled = false;
                    this.emailCodeText = '发送验证码';
                }
            }, 1000);
        },
        judgeIsLogin() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            this.isLoggedIn = userInfo != null;
            if (this.isLoggedIn) {
                this.userInfo = userInfo;
            }
        },
        showLoginDialog() {
            this.loginDialogVisible = true;
            this.getCode();
        },
        showRegisterDialog() {
            this.registerDialogVisible = true;
            this.getCode();
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getLogin(this.loginForm).then(res => {
                        this.$message.success('登录成功');
                        localStorage.setItem('Authorization', res.token);
                        // 获取用户信息
                        getUserInfo().then(userRes => {
                            this.userInfo = userRes.user;
                            localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
                            this.isLoggedIn = true;
                            this.loading = false;
                            this.loginDialogVisible = false;
                            // 清空表单
                            this.$refs.loginForm.resetFields();
                        }).catch(err => {
                            this.loading = false;
                            console.log(err);
                        });
                    }).catch(err => {
                        this.loading = false;
                    })
                } else {
                    return false;
                }
            });
        },
        handleRegister() {
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getRegister(this.registerForm).then(res => {
                        this.$message.success('注册成功，请登录');
                        this.loading = false;
                        this.registerDialogVisible = false;
                        // 清空表单
                        this.$refs.registerForm.resetFields();
                    }).catch(err => {
                        this.loading = false;
                    })
                } else {
                    return false;
                }
            });
        },
        logout() {
            getLogout().then(res => {
                this.$store.commit('SET_USERINFO', null);
                localStorage.removeItem('Authorization');
                localStorage.removeItem('userInfo');
                this.isLoggedIn = false;
                this.$message.success('已退出登录');
            })
        },
    }
}
</script>

<style scoped>
.nav-bar {
    height: 50px;
    background-color: #fff;
    padding: 0 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .05);
    z-index: 1000;
    box-sizing: border-box;
}

.nav-menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    cursor: pointer;
}

.nav-menu-item-title {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 50px;
}

.nav-menu-item {
    margin-right: 50px;
}

/* 弹窗样式 */
.el-dialog__body {
    padding: 20px 30px;
}

.el-form-item {
    margin-bottom: 20px;
}

.user-section {
    display: flex;
    align-items: center;
}

.delivery-records {
    max-height: 400px;
    overflow-y: auto;
}

::v-deep .logo .el-image__inner{
    width: 170px
}

.delivery-records h3 {
    margin-bottom: 15px;
    text-align: center;
}

.el-dropdown-link {
    cursor: pointer;
    display: flex;
    align-items: center;
    font-size: 0.9rem;
}

.el-dropdown-link span {
    margin-left: 10px;
}

.login-code-img {
    height: 38px;
}


.login-code {
    width: 33%;
    height: 38px;
    float: right;
}

::v-deep .el-button--medium.is-round {
    padding: 10px 10px;
}
</style>